import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import imgTheme1 from '@/static/images/theme1.png'
import imgTheme2 from '@/static/images/theme2.png'

interface HistoryItem {
  expression: string
  result: string
}

// 主题集
const themeList = [
  {
    name: 't1',
    cursorColor: '#f09a37',
    numColor: '#606060',
    numBgColor: 'linear-gradient(200deg, rgb(239,239,239), rgb(224,224,224))',
    operatorColor: '#ffffff',
    operatorBgColor: 'linear-gradient(200deg, rgb(195, 195, 195), rgb(171, 171, 171))',
    equalColor: '#ffffff',
    equalBgColor: 'linear-gradient(200deg, rgb(242,183,72), rgb(240,158,58))',
    themeImg: imgTheme1,
  },
  {
    name: 't2',
    cursorColor: '#a559dd',
    numColor: '#636e74',
    numBgColor: '#fff',
    operatorColor: '#490f7d',
    operatorBgColor: '#e2d7e8',
    equalColor: '#fff',
    equalBgColor: '#8e3cdf',
    themeImg: imgTheme2,
  },
]
const initState = {
  openBtnAudio: false, // 是否开启按钮音效
  openBtnVibrate: false, // 是否开启按钮震动
  showComma: false, // 是否显示千分位
  isEqualClear: false, // 点击等号是否清空算式框
  historyList: [], // 历史记录
  curTheme: 't1', // 当前主题
}

export const useCalculatorStore = defineStore(
  'calculator',
  () => {
    const historyList = ref(initState.historyList)
    const openBtnAudio = ref(initState.openBtnAudio)
    const openBtnVibrate = ref(initState.openBtnVibrate)
    const showComma = ref(initState.showComma)
    const isEqualClear = ref(initState.isEqualClear)
    const curTheme = ref(initState.curTheme)

    const addHistory = (item: HistoryItem) => {
      historyList.value.push(item)
    }

    const clearHistory = () => {
      historyList.value = []
    }

    const vibrateShort = () => {
      if (openBtnVibrate.value) {
        uni.vibrateShort({
          type: 'medium',
        })
      }
    }

    const curThemeOption = computed(() => {
      const findItem = themeList.find((item) => item.name === curTheme.value)
      return findItem
    })

    return {
      historyList,
      addHistory,
      clearHistory,
      openBtnAudio,
      openBtnVibrate,
      showComma,
      isEqualClear,
      vibrateShort,
      themeList,
      curTheme,
      curThemeOption,
    }
  },
  {
    persist: {
      paths: [
        'historyList',
        'openBtnAudio',
        'openBtnVibrate',
        'showComma',
        'curTheme',
        'isEqualClear',
      ],
    },
  },
)
